

declare @voucherno int
select vouwordid,voucherno,IDENTITY(int,1,1) as bdtlno into #tmp  
  from tfb_voucher where vouyearmonth=201404 and vouwordid=1
  order by vouwordid,voucherno
select top 1 @voucherno=voucherno from #tmp where voucherno<>bdtlno order by vouwordid,voucherno
if @voucherno is null
  select @voucherno=max(voucherno) from tfb_voucher where vouyearmonth=201404 and vouwordid=1
select @voucherno
drop table #tmp

